package demo.druid.utils;

import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

public class JDBCUtils {
    public static DataSource ds;

    static {
        Properties properties = new Properties();
        /**
         * 利用反射获取类加载器，以此来得到加载项目中的其他文件
         */
        InputStream resourceAsStream = JDBCUtils.class.getClassLoader()
                .getResourceAsStream("druid.properties");
        try {
            // 加载配置文件 druid.properties
            properties.load(resourceAsStream);
            // 获取连接池对象
            ds = DruidDataSourceFactory.createDataSource(properties);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (resourceAsStream != null) {
                try {
                    resourceAsStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 从数据库连接池工厂中获取连接池对象
     *
     * @return
     */

    public static DataSource getDataSource() {
        return ds;
    }

    /**
     * 从连接池中获取一个数据库的连接
     *
     * @return
     * @throws SQLException
     */

    public static Connection getConnection() throws SQLException {
        return ds.getConnection();
    }

    public static void close(ResultSet set, Connection connection, Statement statement) {
        if (set != null) {
            try {
                set.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
            set = null;
        }
        if (connection != null) {
            try {
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
            connection = null;
        }
        if (statement != null) {
            try {
                statement.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
            statement = null;
        }
    }
}
